package com.deep.hystrix.controller;

import com.deep.hystrix.client.ProviderClient;
import com.deep.hystrix.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
//@DefaultProperties(defaultFallback = "dept_Global_FallbackMethod") //全局的服务降级方法
public class DeptController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private ProviderClient providerClient;

    @Value("${server.port}")
    private String serverPort;


    @RequestMapping(value = "/dept/hystrix/ok/{id}")
    public String deptInfo_Ok(@PathVariable("id") Integer id) {
        String result = deptService.deptInfo_Ok(id);
        log.info("端口号：" + serverPort + " result:" + result);
        return result + "，   端口号：" + serverPort;
    }

    // Hystrix 服务超时降级
    @RequestMapping(value = "/dept/hystrix/timeout/{id}")
    public String deptInfo_Timeout(@PathVariable("id") Integer id) {
        String result = deptService.deptInfo_Timeout(id);
        log.info("端口号：" + serverPort + " result:" + result);
        return result + "，   端口号：" + serverPort;
    }

    @RequestMapping(value = "/dept/{name}")
    public String echo(@PathVariable(name = "name") String name) {
        return providerClient.echo(name);
    }

    @RequestMapping(value = "/dept/timeout")
    public String timeout() {
        return providerClient.timeout();
    }

    @RequestMapping(value = "/dept/error")
    public String error() {
        return providerClient.error();
    }

    /**
     * 全局的 fallback 方法，
     * 回退方法必须和 hystrix 的执行方法在相同类中
     *
     * @DefaultProperties(defaultFallback = "dept_Global_FallbackMethod") 类上注解，请求方法上使用 @HystrixCommand 注解
     */
    public String dept_Global_FallbackMethod() {
        return "C语言中文网提醒您，运行出错或服务端系统繁忙，请稍后再试！（客户端全局回退方法触发,）";
    }


    // Hystrix 服务熔断
    @RequestMapping(value = "/dept/hystrix/circuit/{id}")
    public String deptCircuitBreaker(@PathVariable("id") Integer id) {
        String result = deptService.deptCircuitBreaker(id);
        log.info("result:" + result);
        return result;
    }
}